package com.cl.ks.utils;

import com.jandar.ds.pojo.DbInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Component
public
class DataSourceMap {
    @Value("${spring.datasource.driver-class-name}")
    String driverClassName;
    @Value("${spring.datasource.url}")
    String url;
    @Value("${spring.datasource.username}")
    String username;
    @Value("${spring.datasource.password}")
    String password;
    public static final Map<String, DataSource> DATA_SOURCE_MAP = new HashMap<>();

    @Autowired
    DataSource dbDataSource;

//    public String getDbCode(DataSource dataSource) {
//        AtomicReference<String> dbCode = new AtomicReference<>();
//
//        DATA_SOURCE_MAP.forEach((key, value) -> {
//            try {
//                if (dbDataSource.getConnection().getSchema().equals(dataSource.getConnection().getSchema())) {
//                    dbCode.set(key);
//                }
//            } catch (SQLException e) {
//                throw new RuntimeException(e);
//            }
//        });
//        return dbCode.get();
//    }

    public DataSource get(DbInfo dbInfo) {
        if (dbInfo == null) {
            return dbDataSource;
        }
        if (DATA_SOURCE_MAP.containsKey(dbInfo.getCode())) {
            return DATA_SOURCE_MAP.get(dbInfo.getCode());
        }
        DataSource dataSource = DataSourceBuilder.create().username(dbInfo.getUsername()).password(dbInfo.getPassword())
                .url(dbInfo.getUrl()).driverClassName(dbInfo.getDrivecalss()).build();
        DATA_SOURCE_MAP.put(dbInfo.getCode(), dataSource);
        return dataSource;
    }
}
